import { Socket } from "socket.io-client";
import io from "socket.io-client";
import appConfig from "../../app.config";
import { InitComponentSingleton } from "./devInitComponent";
import { ParamsType } from "@/types/model";

export class WebSocketSingleton {
  private static instance: WebSocketSingleton;
  private socket: Socket | null = null;
  public isInitData: boolean = true; // 添加自定义属性

  private constructor() {
    // 初始化socket连接
    this.socket = io(`http://localhost:${appConfig.MOCK_PORT}/`, {
      reconnectionAttempts: 1, // 例如，尝试重连1次
      reconnectionDelay: 500, // 初始重连的延迟时间毫秒
    });

    // 监听连接错误事件
    this.socket.on("connect_error", () => {
      console.log("可执行npm run mock启动数据模拟服务");
      // 这里可以添加更多的错误处理逻辑，例如退回到一个安全的应用状态、重试机制或者用户通知等
    });

    // 连接成功事件
    this.socket.on("connect", () => {
      console.log("WebSocket连接成功");
    });

    // 数据消息事件
    this.socket.on("message", (msg) => {
      const InitComponent = InitComponentSingleton.getInstance();
      if (this.isInitData) {
        InitComponent.init(msg);
      } else {
        InitComponent.update(msg);
      }
      if (this.isInitData) this.isInitData = false;
    });

    // 其他逻辑...
  }

  public static getInstance(): WebSocketSingleton {
    if (!WebSocketSingleton.instance) {
      WebSocketSingleton.instance = new WebSocketSingleton();
    }
    return WebSocketSingleton.instance;
  }

  public sendMessage(data: ParamsType) {
    if (this.socket) {
      const json = JSON.stringify(data);
      this.socket.emit("send_message", json);
    }
  }
}
